//
//  HLDownloadMananger.m
//  Vision
//
//  Created by HarwordLiu on 16/4/6.
//  Copyright © 2016年 Rilma.Liu. All rights reserved.
//

#import "HLDownloadMananger.h"
#import <FMDB.h>

@interface HLDownloadMananger ()

@property (nonatomic, strong) NSMutableArray<MyEyesCellModel *> *arrCollectionModel;
@property (nonatomic, strong) FMDatabase *dataBase;


@end

@implementation HLDownloadMananger
static HLDownloadMananger *mananger;
+ (instancetype)sharedMananger {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mananger = [[HLDownloadMananger alloc] init];

    });
    return mananger;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.downLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        [self creatTableSqlite];

    }
    return self;
}


#warning 判断未完成
- (BOOL)downLoadMovie:(MyEyesCellModel *)model{
    [self collectionMyEyesCellModel:model];
    return YES;
}

- (NSURLSessionDownloadTask *)downTask {
    if (_downTask) {
        return _downTask;
    }
    else{
        NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:[NSURL URLWithString:@""]];;
        return task;
    }
}

- (BOOL)resume_ {
    if (self.downTask.state == NSURLSessionTaskStateRunning) {
        return NO;
    } else {
        [self creatTableSqlite];
        MyEyesCellModel *model = self.arrCollectionModel[0];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.playUrl] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0f];
        self.downTask = [self.downLoadSession downloadTaskWithRequest:request];
        
        [self.downTask resume];
    }
    return YES;
}

- (void)cancelDownLoad {
    
}

#pragma mark - 下载delegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    double currentProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;
    
    
    NSLog(@"%f", currentProgress);
    
    [self.delegate changeProgress:currentProgress WithModel:self.arrCollectionModel[0]];
    
    
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"%@", location);
    [self deleteFromSqliteWithModel:self.arrCollectionModel[0]];
    if (self.arrCollectionModel.count > 0) {
        [self resume_];
    }
}

- (void)loadLocationWithData:(NSData *)data ORWith:(NSURL *)url {
    if (data != nil) {
        MyEyesCellModel *model = self.arrCollectionModel[0];
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
        NSString *file = [documentsPath stringByAppendingString:[NSString stringWithFormat:@"\%ld.mp4", model.ID]];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        BOOL remove  = [manager removeItemAtPath:file error:nil];
        [data writeToFile:file atomically:YES];
        
        

    } else if (url != nil) {
        MyEyesCellModel *model = self.arrCollectionModel[0];
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
        NSString *file = [documentsPath stringByAppendingString:[NSString stringWithFormat:@"\%ld.mp4", model.ID]];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        BOOL remove  = [manager removeItemAtPath:file error:nil];
        BOOL success = [manager copyItemAtPath:url.path toPath:file error:nil];
        NSLog(@"remove = %d, success = %d", remove, success);

        

    }
}



#pragma mark - 建表存储等待下载


- (void)creatTableSqlite {
    self.arrCollectionModel = [NSMutableArray array];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingString:@"/Vision.sqlite"];
    NSLog(@"%@", path);
    FMDatabase *dataBase = [FMDatabase databaseWithPath:path];
    self.dataBase = dataBase;
    BOOL open = [dataBase open];
    if (open) {
        [dataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS t_WaitDownloadModel (ID integer, duration integer, idx integer, date integer, title text, webUrl text, rawWebUrl text, playUrl text, descriptionText text, category text, coverBlurred text, coverForFeed text, coverForDetail text, coverForSharing text, collection integer, collectionCount integer, shareCount integer, replyCount integer, playCount integer, progress integer)"];
        
        FMResultSet *result = [dataBase executeQuery:@"SELECT * FROM t_WaitDownloadModel ORDER BY date DESC"];
        while (result.next) {
            MyEyesCellModel *model = [[MyEyesCellModel alloc] init];
            model.ID = [result intForColumn:@"ID"];
            model.duration = [result intForColumn:@"duration"];
            model.idx = [result intForColumn:@"idx"];
            model.date = [result intForColumn:@"date"];
            model.consumptionModel.collectionCount = [result intForColumn:@"collectionCount"];
            model.consumptionModel.shareCount = [result intForColumn:@"shareCount"];
            model.consumptionModel.replyCount = [result intForColumn:@"replyCount"];
            model.consumptionModel.playCount = [result intForColumn:@"playCount"];
            model.collection = [result intForColumn:@"collection"];
            
            model.title = [result stringForColumn:@"title"];
            model.webUrl = [result stringForColumn:@"webUrl"];
            model.rawWebUrl = [result stringForColumn:@"rawWebUrl"];
            model.playUrl = [result stringForColumn:@"playUrl"];
            model.descriptionText = [result stringForColumn:@"descriptionText"];
            model.category = [result stringForColumn:@"category"];
            model.coverBlurred = [result stringForColumn:@"coverBlurred"];
            model.coverForFeed = [result stringForColumn:@"coverForFeed"];
            model.coverForDetail = [result stringForColumn:@"coverForDetail"];
            model.coverForSharing = [result stringForColumn:@"coverForSharing"];
            
            model.progress = [result intForColumn:@"progress"];
            
            [self.arrCollectionModel addObject:model];
        }
        
        [dataBase close];
    }
}

- (void)collectionMyEyesCellModel:(MyEyesCellModel *)model {
    [self.arrCollectionModel addObject:model];
    ConsumptionModel *modelConsunmp = model.consumptionModel;
    BOOL open = [self.dataBase open];
    if (open) {
        modelConsunmp.shareCount = 0;
        BOOL result =[self.dataBase executeUpdate:@"INSERT INTO t_WaitDownloadModel (ID, duration, idx, date, title, webUrl, rawWebUrl, playUrl, descriptionText, category, coverBlurred, coverForFeed, coverForDetail, coverForSharing, collection, collectionCount, shareCount, replyCount, playCount, progress) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [NSNumber numberWithInteger:model.ID], [NSNumber numberWithInteger:model.duration], [NSNumber numberWithInteger:model.idx], [NSNumber numberWithInteger:model.date], model.title, model.webUrl, model.rawWebUrl, model.playUrl, model.descriptionText, model.category, model.coverBlurred, model.coverForFeed, model.coverForDetail, model.coverForSharing, [NSNumber numberWithInteger:model.collection], [NSNumber numberWithInteger:model.consumptionModel.collectionCount], [NSNumber numberWithInteger:model.consumptionModel.shareCount], [NSNumber numberWithInteger:model.consumptionModel.replyCount], [NSNumber numberWithInteger:model.consumptionModel.playCount], [NSNumber numberWithFloat:model.progress]];
        NSLog(@"%d", result);
        
        [self.dataBase close];
        
    }
}

- (void)deleteFromSqliteWithModel:(MyEyesCellModel *)model {
    BOOL open = [self.dataBase open];
    MyEyesCellModel *removeModel = [[MyEyesCellModel alloc] init];
    for (MyEyesCellModel *tempModel in self.arrCollectionModel) {
        if (tempModel.duration == model.duration) {
            removeModel = tempModel;
        }
    }
    [self.arrCollectionModel removeObject:removeModel];
    if (open) {
        BOOL result = [self.dataBase executeUpdateWithFormat:@"DELETE FROM t_WaitDownloadModel WHERE title = %@", model.title];
        NSLog(@"%d", result);
    }
    
    
}




@end
